<?php

/**
 * @name ProductController
 * @desc 控制器
 */
class ProductController extends UserCommonController
{
    //首页商品列表
    public function mallAction (){
        $params = $this->post();
        //店铺信息
        $shopInfo = ShopModel::getSingleton()->find(['shop_id'=> $this->user_info['offline_shop_id']], 'shop_status');
        if($shopInfo['shop_status'] == 0){
            $this->ajaxReturn(431, '该店铺暂时无法访问');
        }

        $cond = ['sps.is_default'=> 1,'sps.shop_id'=> $this->user_info['offline_shop_id'], 'p.is_show'=> 1];
        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();
        $list = [];
        //智能推荐
        if($params['cate_id'] == 0){
            $list = $shopProductSpecsModel->db
                ->field('sps.id,sps.shop_spec_stock_total,sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,ps.point,p.product_id,p.product_name,p.cover_img,p.gift_point,c.cate_title')
                ->alias('sps')
                ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
                ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
                ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
                ->where_c($cond)
                ->order('ps.point desc')
                ->limit(0, 10)
                ->select();
        }

        //新品
        if($params['cate_id'] == 1){
            $list = $shopProductSpecsModel->db
                ->field('sps.update_time,sps.create_time,sps.id,sps.shop_spec_stock_total,sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,ps.point,p.product_id,p.product_name,p.cover_img,p.gift_point,c.cate_title')
                ->alias('sps')
                ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
                ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
                ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
                ->where_c($cond)
                ->order('sps.update_time desc, sps.create_time desc')
                ->limit(0, 10)
                ->select();
        }

        //热销
        if($params['cate_id'] == 2){
            $list = $shopProductSpecsModel->db
                ->field('sps.id,sps.shop_spec_stock_total,sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,ps.point,p.product_id,p.product_name,p.cover_img,p.gift_point,c.cate_title')
                ->alias('sps')
                ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
                ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
                ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
                ->where_c($cond)
                ->order('sps.shop_sale_num desc')
                ->limit(0, 10)
                ->select();
        }


        foreach($list as &$val){
            $val['product_name'] = $val['product_name'] .' '. $val['spec_name_full'];
        }

        $data = [
            'list' => $list,
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //商品列表
    public function listAction(){
        $params = $this->post();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $cond = ['sps.is_default'=> 1,'sps.shop_id'=> $this->user_info['offline_shop_id'], 'p.is_show'=> 1];
        if(isset($params['product_name']) && trim($params['product_name'])){
            $cond['p.product_name#like'] = '%' . $params['product_name']. '%';
        }
        if(isset($params['cate_id']) && trim($params['cate_id'])){
            $cond['p.cate_id'] = $params['cate_id'];
        }
//        $cond = "sps.shop_id = ".$this->user_info['offline_shop_id'];
//        if(isset($params['product_name']) && trim($params['product_name'])){
//            $cond .= " AND p.product_name LIKE ".$params['product_name']."%";
//        }
//        if(isset($params['cate_id']) && trim($params['cate_id'])){
//            $cond .= " AND p.cate_id = ".$params['cate_id'];
//        }

        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();
//        $sql = "SELECT *, SUM(shop_spec_stock) as stock_num  FROM (SELECT sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,p.product_id,p.product_name,p.cover_img,p.gift_point,c.cate_title
//FROM v_shop_product_specs sps
//left join v_product_specs ps ON sps.spec_id = ps.spec_id
//left join v_product p ON p.product_id = sps.product_id
//left join v_cate c ON c.cate_id = p.cate_id
//WHERE  $cond ORDER BY sps.is_default DESC) t GROUP BY product_id  LIMIT ".($page - 1) * $row.','.$row;
//        print_r($sql);exit;

        $list = $shopProductSpecsModel->db
            ->field('sps.id,sps.shop_spec_stock_total,sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,ps.point,p.product_id,p.product_name,p.cover_img,p.gift_point,p.sub_name,c.cate_title')
            ->alias('sps')
            ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
            ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
            ->where_c($cond)
            ->order('sps.is_default desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $shopProductSpecsModel->db
            ->field('sps.shop_spec_stock,ps.spec_name_full,p.product_name,c.cate_title')
            ->alias('sps')
            ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
            ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
            ->where_c($cond)
            ->count();
//print_r($list);exit;
        foreach($list as &$val){
            $val['product_name'] = $val['product_name'] .' '. $val['spec_name_full'];
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //云端商品
    public function cloudAction(){
        $params = $this->post();

        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();
        //店铺仓库为零的商品
        $zreoList = $shopProductSpecsModel->findAll(['shop_id'=> $this->user_info['offline_shop_id'], 'shop_spec_stock'=> 0], 'spec_id');

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $cond = ['sps.is_default'=> 1,'sps.shop_id'=> $this->user_info['offline_shop_id'], 'p.is_show'=> 1];
        if(isset($params['product_name']) && trim($params['product_name'])){
            $cond['p.product_name#like'] = $params['product_name']. '%';
        }
        if(isset($params['cate_id']) && trim($params['cate_id'])){
            $cond['p.cate_id'] = $params['cate_id'];
        }



        $list = $shopProductSpecsModel->db
            ->field('sps.id,sps.shop_spec_stock_total,sps.is_show,sps.spec_id,ps.spec_name_full,ps.unit_money,ps.point,p.product_id,p.product_name,p.cover_img,p.gift_point,p.sub_name,c.cate_title')
            ->alias('sps')
            ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
            ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
            ->where_c($cond)
            ->order('sps.is_default desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $shopProductSpecsModel->db
            ->alias('sps')
            ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['product', 'p'], ['p.product_id'=> 'sps.product_id'], 'left join')
            ->join(['cate', 'c'], ['c.cate_id'=> 'p.cate_id'], 'left join')
            ->where_c($cond)
            ->count();
//print_r($list);exit;
        foreach($list as &$val){
            $val['product_name'] = $val['product_name'] .' '. $val['spec_name_full'];
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //详情
    public function detailAction(){
        $params = $this->post();

        if(!isset($params['spec_id']) || !intval($params['spec_id'])){
            $this->ajaxReturn(400, '未获取到规格商品ID');
        }

        //规格
        $productSpecModel = ProductSpecsModel::getSingleton();
        $productSpecDetail = $productSpecModel->find(['spec_id'=> $params['spec_id']]);

        //判断是否是登陆用户所属于店铺
        $productModel = ProductModel::getSingleton();
        $detail = $productModel->find(['product_id'=> $productSpecDetail['product_id']]);
        if(!$detail){
            $this->ajaxReturn(400, '商品不存在');
        }

        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();
        if(!isset($params['cloud'])){
            $shopProductSpecDetail = $shopProductSpecsModel->find(['shop_id'=> $this->user_info['offline_shop_id'], 'spec_id'=> $params['spec_id']]);
            if(!$shopProductSpecDetail){
                $this->ajaxReturn(400, '商品非店铺所有，请联系店铺购买');
            }
        }
//        if($detail['is_show'] == 0){
//            $this->ajaxReturn(400, '商品已下架');
//        }

        //获取所有规格列表
        $specCatsModel = SpecCatsModel::getSingleton();
        $tempList = $specCatsModel->db
            ->alias('sc')
            ->field('*')
            ->join(['spec_items', 'si'], ['sc.cat_id'=> 'si.cat_id'], 'inner join')
            ->where_c(['si.product_id'=> $productSpecDetail['product_id']])
            ->select();
        $specsTemp = [];
        foreach ($tempList as $val){
            $specsTemp[$val['cat_id']]['k'] = $val['cat_name'];
            $specsTemp[$val['cat_id']]['v'][] = ['id'=> $val['item_id'], 'name'=> $val['item_name']];
            $specsTemp[$val['cat_id']]['ext'][$val['item_id']] = ['id'=> $val['item_id'], 'name'=> $val['item_name']];
            $specsTemp[$val['cat_id']]['k_s'] = 's'.$val['cat_id'];
        }
        $specs = [];
        foreach ($specsTemp as $val){
            $specs[] = $val;
        }
//        foreach (reset($specs)['v'] as &$val){
//            $val['imgUrl'] = 'https://img.yzcdn.cn/2.jpg';
//        }

        //所有已添加的商品规格
        if(isset($params['cloud'])){
            //云端商品
            $tempList = $productSpecModel->db
                ->field('is_default,spec_id,spec_stock as shop_spec_stock,spec_stock_total as shop_spec_stock_total,unit_money,spec_ids')
                ->where(['product_id'=> $productSpecDetail['product_id'], 'is_show'=> 1])
                ->select();
        }else {
            //店铺商品
            $tempList = $shopProductSpecsModel->db
                ->alias('sps')
                ->field('sps.is_default,sps.spec_id,sps.shop_spec_stock,sps.shop_spec_stock_total,ps.unit_money,ps.spec_ids')
                ->join(['product_specs', 'ps'], ['ps.spec_id'=> 'sps.spec_id'], 'left join')
                ->where_c(['sps.product_id'=> $productSpecDetail['product_id'], 'sps.shop_id'=> $shopProductSpecDetail['shop_id'], 'sps.is_show'=> 1])
                ->select();
        }

        $productSpecs = [];
        $stock_num_total = 0;         //各规格总库存
        $defaultSpec = [];
        foreach ($tempList as $val){
            $temp = [
                'id'    => $val['spec_id'],
                'price' => $val['unit_money'] * 100,
                'stock_num' => $val['shop_spec_stock']
            ];
            $sArr = explode('_', $val['spec_ids']);
            foreach ($sArr as $key=>$vv){
                $arr = explode('#', $vv);
                $temp[$arr[0]] = $arr[1];
            }
            $productSpecs[] = $temp;
            $stock_num_total += intval($val['shop_spec_stock']);

            //取默认规格展示在详情页面
            if($val['is_default'] == 1){
                $spec_name_full = '';
                foreach ($sArr as $vv){
                    $arr = explode('#', $vv);
                    $cat_id = str_replace('s', '', $arr[0]);
                    $spec_name_full .= ' '.$specsTemp[$cat_id]['ext'][$arr[1]]['name'];
                }
                $defaultSpec['spec_name_full'] = $spec_name_full;
                $defaultSpec['price'] = $val['unit_money'];
                $defaultSpec['stock_num'] = $val['shop_spec_stock'];
                $defaultSpec['spec_id'] = $val['spec_id'];
                $stock_num_total = $val['shop_spec_stock_total'];
            }
        }

        $sku = [
            'tree'=> $specs,
            'list'=> $productSpecs,
            'price' => $defaultSpec['price'],
            'stock_num' => $stock_num_total,
            'collection_id' => reset($productSpecs)['id'],
            'none_sku'  => false,   //是否无规格商品
            'hide_stock'    => false    //是否隐藏剩余库存
        ];

        $skuGroup = [
            'showBase'  => false,
            'sku'   => $sku,
            'goods' => ['title'=> $detail['product_name'].$defaultSpec['spec_name_full'], 'picture'=> $detail['cover_img']],
            'goodsId'   => $detail['product_id'],
            'quota'     => $detail['quota_num_top'],    //限购数量
            'quotaUsed' => 0,                           //已购买数量
            'resetStepperOnHide'    => true,
            'resetSelectedSkuOnHide'    => true,
            'disableStepperInput'   => false,
            'closeOnClickOverlay'   => true,
            'showAddCartBtn'    => false,
            'buyText'       => '确定'
        ];

        $detail['spec_id'] = $defaultSpec['spec_id'];
        $detail['product_name'] = $skuGroup['goods']['title'];
        $detail['spec_name_full'] = '规格：'.$defaultSpec['spec_name_full'];
        $detail['unit_money'] = $skuGroup['sku']['price'];
        $detail['stock_num_total'] = $stock_num_total;
        $detail['stock_num'] = $defaultSpec['stock_num'];
        $detail['gallery_img'] = json_decode($detail['gallery_img']);


        $returnDAta = [
            'detail'    => $detail,
            'skuGroup'  => $skuGroup
        ];
        $this->ajaxReturn(0, 'success', $returnDAta);
    }

    //分类列表
    public function catelistAction(){
        $cateModel = CateModel::getSingleton();
        $list = $cateModel->findAll(['is_show'=> 1], 'cate_id, cate_title, sort', 'sort desc');
        $this->ajaxReturn(0, '', $list);
    }
}
